package com.boarsoft.boar.server.biz;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.entity.AppInfo;
import com.boarsoft.boar.entity.AppInst;
import com.boarsoft.boar.entity.ServerInfo;
import com.boarsoft.boar.server.ServerBiz;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component
public class ServerBizImpl extends SimpleBizImpl implements ServerBiz {

	@Override
	@Transactional(readOnly = true)
	public PagedResult<ServerInfo> list(String projId, String env, String key, String orderBy, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from ").append(ServerInfo.class.getName());
		sb.append(" where 1=1");
		if (Util.strIsNotEmpty(projId)) {
			sb.append(" and projId='").append(projId).append("'");
		}
		if (Util.strIsNotEmpty(env) && !"ALL".equalsIgnoreCase(env)) {
			sb.append(" and env='").append(env).append("'");
		}
		// if (Util.strIsNotEmpty(exAppCode)) {
		// // 查询未部署指定APP的服务器
		// sb.append(" and not exists (select i.id from ");
		// sb.append(AppInst.class.getName()).append(" i join i.app a");
		// sb.append(" where a.code='").append(exAppCode);
		// sb.append("' and i.serverId=s.id)");
		// }
		if (Util.strIsNotEmpty(key)) {
			sb.append("and (code like '%").append(key);
			sb.append("%' or name like '%").append(key);
			sb.append("%' or ip like '%").append(key);
			sb.append("%')");
		}
		String ql = sb.toString();
		int total = dao.getTotal("select count(id)".concat(ql));
		if (Util.strIsNotEmpty(orderBy)) {
			// String[] ob = ("s." + orderBy).replaceAll(",", ",").split(",");
			// sb.append(Util.array2str(ob, ", s."));
			sb.append(" order by ").append(orderBy);
		} else {
			sb.append(" order by ip");
		}
		List<ServerInfo> lt = dao.list(sb.toString(), pageNo, pageSize);
		return new PagedResult<ServerInfo>(total, lt, pageNo, pageSize);
	}

	/**
	 * ###查询应用未规划服务器 select s.* from server_info s where s.cId not in (select
	 * ai.cServerId from app_inst ai where ai
	 * .cAppId='9483859e5841dc1d015841eedf9b0002') and
	 * s.cProjId='9483859e58761c610158767a39d50004'
	 */
	@Override
	@Transactional(readOnly = true)
	public PagedResult<ServerInfo> list(String projId, String appId, String env, String key, String orderBy, int pageNo,
			int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from ").append(ServerInfo.class.getName());
		sb.append(" s where s.id not in (select ai.serverId from ").append(AppInst.class.getName())
				.append(" ai where ai.appId='").append(appId).append("')");
		if (Util.strIsNotEmpty(projId)) {
			sb.append(" and s.projId='").append(projId).append("'");
		}
		if (Util.strIsNotEmpty(env) && !"ALL".equalsIgnoreCase(env)) {
			sb.append(" and s.env='").append(env).append("'");
		}
		// if (Util.strIsNotEmpty(exAppCode)) {
		// // 查询未部署指定APP的服务器
		// sb.append(" and not exists (select i.id from ");
		// sb.append(AppInst.class.getName()).append(" i join i.app a");
		// sb.append(" where a.code='").append(exAppCode);
		// sb.append("' and i.serverId=s.id)");
		// }
		if (Util.strIsNotEmpty(key)) {
			sb.append("and (s.code like '%").append(key);
			sb.append("%' or s.name like '%").append(key);
			sb.append("%' or s.ip like '%").append(key);
			sb.append("%')");
		}
		String ql = sb.toString();
		int total = dao.getTotal("select count(s.id)".concat(ql));
		if (Util.strIsNotEmpty(orderBy)) {
			// String[] ob = ("s." + orderBy).replaceAll(",", ",").split(",");
			// sb.append(Util.array2str(ob, ", s."));
			sb.append(" order by ").append(orderBy);
		} else {
			sb.append(" order by s.ip");
		}
		List<ServerInfo> lt = dao.list(sb.toString(), pageNo, pageSize);
		return new PagedResult<ServerInfo>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional
	public void save(ServerInfo o) {
		dao.save(o);
	}

	@Override
	@Transactional
	public void update(ServerInfo o) {
		dao.merge(o);
	}

	@Override
	@Transactional
	public void delete(String id) {
		// dirBiz.delete(id);
		dao.delete(ServerInfo.class, id);
	}

	@Override
	@Transactional
	public void deleteByProjId(String pid) {
		String hsql = "delete from " + ServerInfo.class.getName() + " where projId='" + pid + "'";
		dao.executeUpdate(hsql);
	}

	@Override
	public ServerInfo get(String id) {
		return (ServerInfo) dao.get(ServerInfo.class, id);
	}

	@Override
	@Transactional
	public boolean start(String id) {
		ServerInfo o = (ServerInfo) dao.get(ServerInfo.class, id);
		if (o.getStatus() != ServerInfo.STATUS_STOPPED)
			return false;
		o.setStatus(ServerInfo.STATUS_RUNNING);
		return true;
	}

	@Override
	@Transactional
	public boolean stop(String id) {
		ServerInfo o = (ServerInfo) dao.get(ServerInfo.class, id);
		if (o.getStatus() != ServerInfo.STATUS_RUNNING)
			return false;
		o.setStatus(ServerInfo.STATUS_STOPPED);
		return true;
	}

	/**
	 * 查询节点（服务器）关联的（已部署的）应用列表
	 *
	 * @param id
	 * @return
	 */
	@Override
	@Transactional(readOnly = true)
	public PagedResult<AppInfo> listApps(String id, String key, String orderBy, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append("and l.id='").append(id).append("'");
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and ( a.code like '%").append(key);
			sb.append("%' or a.name like '%").append(key);
			sb.append("%' or a.memo like '%").append(key);
			sb.append("%')");
		}
		String wl = new StringBuilder().append("select count(l) from ").append(AppInfo.class.getName())
				.append(" a join a.insts l").append(" where 1=1 ").append(sb).toString();
		log.info("===============", wl);
		int total = dao.getTotal(wl);
		if (Util.strIsNotEmpty(orderBy)) {
			String ob = Util.array2str(("l." + orderBy).replaceAll(",", ",").split(","), ",");
			sb.append(" order by ").append(ob);
			// sb.append(" order by l.").append(orderBy);
		} else {
			sb.append(" order by l.name");
		}
		String ql = new StringBuilder().append("select a from ").append(AppInfo.class.getName()).append(" a join a.insts l")
				.append(" where 1=1 ").append(sb).toString();
		log.info("===============", ql);
		List<AppInfo> lt = dao.list(ql, pageNo, pageSize);
		return new PagedResult<AppInfo>(total, lt, pageNo, pageSize);
	}

	/**
	 * 查询节点（服务器）关联的（已部署的）应用列表 结果集中有app和appInst，返回类型为PagedResult<AppInst>
	 *
	 * @param serverId
	 * @return
	 */
	@Override
	public PagedResult<AppInst> listAppsRich(String serverId, String key, String orderBy, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append("and o.serverId='").append(serverId).append("'");
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and ( a.code like '%").append(key);
			sb.append("%' or a.name like '%").append(key);
			sb.append("%' or a.memo like '%").append(key);
			sb.append("%' )");
		}
		String wl = new StringBuilder().append("select count(o) from ").append(AppInst.class.getName())
				.append(" o join o.app a").append(" where 1=1 ").append(sb).toString();
		log.info("===============", wl);
		int total = dao.getTotal(wl);
		if (Util.strIsNotEmpty(orderBy)) {
			String ob = Util.array2str(("a." + orderBy).replaceAll(",", ",").split(","), ",");
			sb.append(" order by ").append(ob);
			// sb.append(" order by l.").append(orderBy);
		} else {
			sb.append(" order by a.name");
		}
		String ql = new StringBuilder().append("select o from ").append(AppInst.class.getName()).append(" o join fetch o.app a")
				.append(" where 1=1 ").append(sb).toString();
		List<AppInst> lt = dao.list(ql, pageNo, pageSize);
		return new PagedResult<AppInst>(total, lt, pageNo, pageSize);
	}

	/**
	 * 根据节点（服务器）Id查询其未关联（未依赖的）的应用信息列表信息
	 */
	@Override
	@Transactional(readOnly = true)
	public PagedResult<AppInfo> listAppsWhereServerNotOnIt(String serverId, String key, String orderBy, int pageNo,
			int pageSize) {
		StringBuilder sb = new StringBuilder();
		StringBuilder keyWord = new StringBuilder();
		if (Util.strIsNotEmpty(key)) {
			keyWord.append(" and (s.code like '%").append(key);
			keyWord.append("%' or s.name like '%").append(key);
			keyWord.append("%' or s.memo like '%").append(key);
			keyWord.append("%' )");
		}

		sb.append("select distinct s from ").append(AppInfo.class.getName()).append(" s,").append(ServerInfo.class.getName())
				.append(" a where s not in elements(a.apps) and a.id='").append(serverId).append("'").append(keyWord)
				.toString();
		StringBuilder sbs = new StringBuilder();
		sbs.append("select count(s.id) from ").append(AppInfo.class.getName()).append(" s,").append(ServerInfo.class.getName())
				.append(" a where s not in elements(a.apps) and a.id='").append(serverId).append("'").append(keyWord)
				.toString();
		int total = dao.getTotal(sbs.toString());
		if (Util.strIsNotEmpty(orderBy)) {
			String ob = Util.array2str(("s." + orderBy).replaceAll(",", ",").split(","), ",");
			sb.append(" order by ").append(ob);
			// sb.append(" order by l.").append(orderBy);
		} else {// 没有排序条件就默认按name排序
			sb.append(" order by s.name");
		}

		List<AppInfo> lt = dao.list(sb.toString(), pageNo, pageSize);
		return new PagedResult<AppInfo>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional(readOnly = true)
	public ServerInfo find(String projId, String ip) {
		String wql = new StringBuilder().append("and projId='")//
				.append(projId).append("' and ip='")//
				.append(ip).append("'").toString();
		return dao.find(ServerInfo.class, wql);
	}
}